<script setup lang="ts">
import {NLayoutSider, NButton} from 'naive-ui'
import 'naive-ui/es/layout/styles'
import 'naive-ui/es/button/styles'
import {SIcon, WatchSizeStrategyConst, SWatchSize} from '@xtail/vue3'
import {ResponsiveWidthConst} from '@xtail/ui'
import ChevronRight from '@iconify/icons-line-md/chevron-right'
import ChevronLeft from '@iconify/icons-line-md/chevron-left'
import type {LayoutSideResponsivePropsType} from './types'

defineOptions({
  name: 'XLayoutSideResponsive'
})

withDefaults(defineProps<LayoutSideResponsivePropsType>(), {
  watchSizeProps: {} as any,
  sideProps: {} as any,
  btnTrigger: true,
  btnTriggerProps: {} as any,
  btnTriggerIconProps: {} as any,
})

const collapsed = defineModel<boolean>('collapsed', {default: false})
const toggleCollapsed = () => collapsed.value = !collapsed.value
const widthUpdateHandlerDefault = (size: number) => {
  collapsed.value = size <= ResponsiveWidthConst.sm
}
</script>

<template>
  <n-layout-sider
    v-bind="{
      bordered: true,
      collapseMode: 'width',
      ...sideProps
    }"
    v-model:collapsed="collapsed"
  >
    <s-watch-size
      class="x-layout-side-responsive"
      v-bind="{
        ...watchSizeProps,
        strategy: watchSizeProps.strategy ?? WatchSizeStrategyConst.WINDOW,
        widthUpdateHandler: watchSizeProps.widthUpdateHandler ?? widthUpdateHandlerDefault
      }"
    >
      <div class="x-layout-side-responsive__content-container">
        <div class="x-layout-side-responsive__content">
          <slot name="content" :collapsed="collapsed"/>
        </div>
      </div>
      <div
        v-if="btnTrigger"
        class="x-layout-side-responsive__btn-trigger"
      >
        <slot
          name="btn-trigger"
          :collapsed="collapsed"
          :toggleCollapsed="toggleCollapsed"
        >
          <n-button
            v-bind="{
              quaternary: true,
              block: true,
              ...btnTriggerProps
            }"
            @click="toggleCollapsed"
          >
            <template #icon>
              <slot name="btn-trigger-icon">
                <s-icon
                  v-bind="{
                    iconProps: {icon: collapsed ? ChevronRight : ChevronLeft},
                    ...btnTriggerIconProps
                  }"
                />
              </slot>
            </template>
          </n-button>
        </slot>
      </div>
    </s-watch-size>
  </n-layout-sider>
</template>

<style lang="scss">
@use './style' as *;
</style>
